package demo

import (
	"a-admin/web/resp"
	"a-common/myerr"
	"a-demo/domain/entity"
	"a-demo/service"
	"fmt"
	"sync"

	"github.com/gofiber/fiber/v2"
)

var (
	senBabyControllerTemp *SenBabyController
	senBabyService        = service.NewSenBabyService()
	senBabyControllerOnce sync.Once
)

type SenBabyController struct{}

func NewSenBabyController() *SenBabyController {
	senBabyControllerOnce.Do(func() {
		senBabyControllerTemp = &SenBabyController{}
	})
	return senBabyControllerTemp
}

// List 分页
func (m *SenBabyController) List(c *fiber.Ctx) error {
	var args entity.SenBabyDto
	if err := c.QueryParser(&args); err != nil {
		return myerr.ERR_SYS_ARGS
	}
	err := args.Validator()
	if err != nil {
		return err
	}

	// 查询
	pageVo, err := senBabyService.List(&args)
	if err != nil {
		return err
	}
	return resp.Resp(c, pageVo)
}

// Get 查
func (m *SenBabyController) Get(c *fiber.Ctx) error {
	id := c.Params("id")
	if id == "" {
		return myerr.ERR_SYS_ARGS
	}
	data, err := senBabyService.Get(id)
	if err != nil {
		return err
	}
	return resp.Resp(c, data)
}

// Del 删
func (m *SenBabyController) Del(c *fiber.Ctx) error {
	ids := c.Params("ids")
	if ids == "" {
		return myerr.ERR_SYS_ARGS
	}
	_, err := senBabyService.Del(ids)
	if err != nil {
		return err
	}
	return resp.Ok(c)
}

// Add 增
func (m *SenBabyController) Add(c *fiber.Ctx) error {
	var args entity.SenBabyDto
	if err := c.BodyParser(&args); err != nil {
		return myerr.ERR_SYS_ARGS
	}
	user := resp.GetUser(c)
	args.CreatedBy = user.Account

	_, err := senBabyService.Add(&args)
	if err != nil {
		return err
	}
	return resp.Ok(c)
}

// Edit 改
func (m *SenBabyController) Edit(c *fiber.Ctx) error {
	var args entity.SenBabyDto
	if err := c.BodyParser(&args); err != nil {
		return myerr.ERR_SYS_ARGS
	}
	user := resp.GetUser(c)
	args.UpdatedBy = user.Account

	_, err := senBabyService.Edit(&args)
	if err != nil {
		return err
	}
	return resp.Ok(c)
}

// Export 导出
func (m *SenBabyController) Export(c *fiber.Ctx) error {
	var args entity.SenBabyDto
	if err := c.QueryParser(&args); err != nil {
		return myerr.ERR_SYS_ARGS
	}

	title := "宝宝档案表"
	f, err := senBabyService.Export(&args, title)
	if err != nil {
		return err
	}
	c.Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, title))
	err = f.Write(c.Response().BodyWriter())
	if err != nil {
		return err
	}
	return nil
}
